// 云函数入口文件
const cloud = require('wx-server-sdk')
var rp = require('request-promise');
const moment = require("moment-timezone")
moment.tz.setDefault("Asia/Shanghai")
const TcbRouter = require('tcb-router');
cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
	const app = new TcbRouter({
		event
	})
	app.use(async (ctx, next) => {
		ctx.data = {}
		ctx.wxContext = cloud.getWXContext()
		await next()
	})
	app.router('getMpErCode', async (ctx, next) => {
		const mpOpenApi = cloud.openapi({
			appid: "wx2b3389aa83cef390"
		})
		ctx.body = mpOpenApi.officialAccount.qrcode.create(event.param)
	})
	app.router('sendMsg', async (ctx, next) => {
		try {
			let res = await db.collection('mp_send').where({
				startTime: _.lte(parseInt(moment().valueOf())),
				endTime: _.gt(parseInt(moment().valueOf())),
			}).get()
			if (res.errMsg != 'collection.get:ok' || !res.data.length) return;
			var taskList = res.data
			taskList.map(async (fv, fk) => {
				fv.personList.map(async (v, k) => {
					let tips = '',
						data = {}
					switch (fv.type) {
						case 'task':
							tips = '您有新的作业，请及时查收'
							data = {
								touser: v.mpOpenid,
								mpTemplateMsg: {
									appid: 'wx2b3389aa83cef390',
									miniprogram: {
										appid: 'wxb80c47c470ca4e38',
										pagepath: fv.page
									},
									data: {
										first: {
											value: '【微飒班管】' + tips
										},
										keyword1: {
											value: fv.className
										},
										keyword2: {
											value: fv.taskTitle
										},
										keyword3: {
											value: '点我查看作业详情'
										},
										remark: {
											value: fv.endDesc
										}
									},
									templateId: 'cyoU_lYdD9rK_xYA1PWq6K-8shaM7o8qX-Ku3sRF3vE'
								}
							}
							break
						case 'notify':
							tips = '您有新的通知，请及时查看'
							data = {
								touser: v.mpOpenid,
								mpTemplateMsg: {
									appid: 'wx2b3389aa83cef390',
									miniprogram: {
										appid: 'wxb80c47c470ca4e38',
										pagepath: fv.page
									},
									data: {
										first: {
											value: '【微飒班管】' + tips
										},
										keyword1: {
											value: fv.className
										},
										keyword2: {
											value: fv.taskTitle
										},
										keyword3: {
											value: '点我查看作业详情'
										},
										remark: {
											value: fv.endDesc
										}
									},
									templateId: 'cyoU_lYdD9rK_xYA1PWq6K-8shaM7o8qX-Ku3sRF3vE'
								}
							}
							break
						case 'activity':
							tips = '您有新的活动，请及时查看'
							data = {
								touser: v.mpOpenid,
								mpTemplateMsg: {
									appid: 'wx2b3389aa83cef390',
									miniprogram: {
										appid: 'wxb80c47c470ca4e38',
										pagepath: fv.page
									},
									data: {
										first: {
											value: '【微飒班管】' + tips
										},
										keyword1: {
											value: fv.taskTitle
										},
										keyword2: {
											value: fv.endDesc
										},
										keyword3: {
											value: fv.className
										},
										remark: {
											value: '点我查看活动详情'
										}
									},
									templateId: 'Tplb4EUis54ve4cNfT1Jkurw_vAZ320k2PEZPkNYW8U'
								}
							}
							break
					}
					const result = await cloud.openapi.uniformMessage.send(
						data)
					let notifySuccessSum = 0,
						notifyFailSum = 0
					if (result.errCode == 0 && result.errMsg ==
						'openapi.templateMessage.send:ok') {
						notifySuccessSum++
					} else {
						notifyFailSum++
					}
					if (k == fv.personList.length - 1) {
						await db.collection('edu_task').where({
							taskId: fv.taskId
						}).update({
							data: {
								notifySuccessSum,
								notifyFailSum,
								sendTime: moment().valueOf()
							}
						})
						await db.collection('mp_send').where({
							_id: fv._id
						}).remove()
					}
				})
			})

		} catch (err) {
			await db.collection('err_list').add({
				data: {
					app: 'edu',
					desc: "通知定时发送",
					errDesc: err,
					createTime: moment().valueOf()
				}
			})
			ctx.body = err
		}
	})
	return app.serve()
}
